import ToolBarView from '@/components/views/toolbar'

// 沙箱
import SandBox from '@/components/views/sandbox'

import QuickToolBarView from '@/components/views/quick-toolbar'
import LeftPaneView from '@/components/views/left-pane'
import RightPaneView from '@/components/views/right-pane'

// TODO 包装成工具
import localForage from 'localforage';

import CustomCanvas from '@/assets/app/design/canvas'

// 视图、参考线、链接上一页、状态、内置组件、我的组件等等
import ProtoViewportView from '@/components/views/proto-viewport'

import { mapState } from 'vuex'

// 可拖拽图形
// import vdr from '@/components/vue-draggabel-resizable'
import '~/components/vue-draggabel-resizable/index.css'

var $this = null

import utils from '@/plugins/utils/utils.js'
window.xxxx = 'xxx2'
export default {
  // 中间件
  middleware: 'design-event-bus',
  components: {
    'tool-bar': ToolBarView,
    'sand-box': SandBox,
    'quick-toolbar': QuickToolBarView,
    'left-pane': LeftPaneView,
    'right-pane': RightPaneView,
    'proto-viewport': ProtoViewportView
  },
  computed: {
    ...mapState({
      leftPane: state=> state.design.view.leftPane
    }),
    keymap() {
      return {
        'space': {
          keydown: this.spaceDown,
          keyup: this.spaceUp
        },
        // '`': this.showHotBox,
        'tab': this.hotBoxHandle,
        'F2': this.changeWidgetTypeHandle,
        'ctrl+s': this.save,
        'ctrl+1': this.hotKeyHandle
        // 'shift': this.changeWidgetTypeHandle
      }
    },
    hotBoxKeymap() {
      let result = {}
      for (let i = 0; i < 10; i++) {
        result[i] = {
          keydown: this.selectWidgetHandle,
          keyup: this.selectWidgetHandle
        }
      }
      return result
    },
    lines() {
      return this.$store.state.design.lines
    },
    moving() {
      // 是否正在拖动组件，true：拖动中，false：停止拖动
      return this.$store.state.design.moving
    },
    designSize() {
      return this.$store.state.design.config.size
    },
    _transformxy() {
      // utils.log('限制',this.$store.state.design.config.transformxy.x,this.$store.state.design.config.transformxy.y)
      return this.$store.state.design.config.transformxy
    }
  },
  created() {
    utils.log('创建页面....')
    // eslint-disable-next-line consistent-this
    $this = this
    // this.$nuxt.$on('view-left-pane', (params) => {
    //   if (params.type == 'show') {
    //     this.visibles
    //   }
    // })
  },
  watch: {
    '$store.state.design.selects': function (selects) {
      utils.log('selects.length', selects.length, selects)
      if (!selects || selects.length == 0 || !selects.length) {
        this.currentSelectWidget = null
        this.position = null
        this.selects = []
        // this.totalWiget = null
      } else {
        // this.totalWiget = this.$store.state.design.totalSelect
        utils.log('totalWiget', this.totalWiget)
        this.selects = window.$design.get(selects)

        this.currentSelectWidget = window.$design.get(selects[0])
        this.position = this.currentSelectWidget.config

        // 选中
      }

      // 触发 重置selects、 unselects、 selectWidgets、 unselectWidgets
      this.$store.commit('design/resetAboutSelects')
    },
    '$store.state.design.totalSelect': function (newValue) {
      utils.log('totalSelect', newValue)
      this.totalWiget = newValue
    },
    '$store.state.design.hover': function (newValue) {
      // utils.log('hover',newValue)
      if (newValue !== null) {
        // 如果选中则，为null
        this.hoverWidget = window.$design.get(newValue)
      } else {
        this.hoverWidget = null
      }
    }
  },
  mounted() {
    return
    console.log(';;;;;;;;;',this.leftPane)
    let store = localForage.createInstance({
      name: 'xxx'
    })
    store.setItem('key', 'value')

    let designView = '#design', widgetList = '#widget-list', widget = '.widget'
    CustomCanvas.create(designView, widgetList, widget)
    $nuxt.$emit('init-design')

    // 滚轴监听 - proto-main-content
    document.getElementById('design').onmousewheel = function (e) {
      utils.log('鼠标滚轴 e', e.wheelDeltaY)
      $nuxt.$emit('move-canvas', {
        offetY: e.wheelDeltaY
      })
      // $this.transformxy.y = $this.transformxy.y + e.wheelDeltaY
      // // 控制大小
      // if($this.designSize.heightHalf <= Math.abs($this.transformxy.y)){
      //     $this.transformxy.y =  $this.transformxy.y > 0 ? $this.designSize.heightHalf:-$this.designSize.heightHalf
      // }
    }

    // document.oncontextmenu = function (e) {
    //     e.preventDefault()
    //     // 执行代码块
    //     utils.log('右键菜单')
    // }

    // 初始化
    // initCanvasWidgetDrag()

    $this.$design = document.getElementById('design')
    $this.$canvas = document.getElementById('widget-list')

    // 按下键盘
    // document.onkeydown = function (e) {
    //   e.preventDefault()
    //   let key = window.event.keyCode

    //   if (document.activeElement.id == 'text_editor') {
    //     // TODO 如果text_editor获取了focus
    //   } else if (key == 32) {
    //     // 按下了空格键
    //     $nuxt.$emit('key-down', key)
    //     // TODO 点击左键
    //     $this.$design.addEventListener('mousedown', $this.clickDrag, false)
    //   } // end 空格
    //   else if (key == 83 && e.ctrlKey) {
    //     //== 83 s键
    //     $this.saveHandler() //;saveProject1()
    //   } else if (key == 18) {
    //     // == 18 alt键
    //     $nuxt.$emit('alt-keydown')

    //     $nuxt.$emit('key-down', key)
    //   } else if (moveMap[key]) {
    //     // 移动
    //     $nuxt.$emit('widget-move', moveMap[key])
    //   } else {
    //     // $nuxt.$emit('key-down', key)
    //     utils.log('按键 - key = ', key)
    //   }
    // }
    // 松开键盘
    // document.onkeyup = function (e) {
    //   let key = window.event.keyCode
    //   $nuxt.$emit('key-up', key)
    //   if (key == 32) {
    //     // 空格
    //     $this.removeEventListener()
    //   }
    // }

    $this.$design.addEventListener('mouseup', function () {
      // utils.log('松开...')
      $this.removeEventListener()
    })


  },
  methods: {
    hotKeyHandle(e) {
      // e.ctrlKey e.key
      console.log('快捷键：', e)
    },
    save() {
      console.log('保存')
    },
    selectWidgetHandle(e) {
      if (e.type == 'keydown') {
        console.log('正在选择：', e.key, e.type)
      }
      if (e.type == 'keyup') {
        console.log('选中：', e.key, e.type)
        this.hotBoxHandle('hide')
      }
    },
    hotBoxHandle(type) {
      if (type == 'hide') {
        this.hotBoxVisible = false
      } else if (type == 'show') {
        this.hotBoxVisible = true
      } else {
        this.hotBoxVisible = !this.hotBoxVisible
      }

      console.log(this.hotBoxVisible ? '打开热盒' : '关闭热盒')
    },
    spaceDown() {
      // TODO 鼠标变手形
      $this.$design.addEventListener('mousedown', $this.clickDrag, false)
    },
    spaceUp() {
      // TODO 鼠标取消手型
      $this.removeEventListener()
    },
    changeWidgetTypeHandle(e) {
      console.log(e)
    },
    isSelect(wid) {
      if (!wid) {
        return false
      }
      let result = this.selects.filter(item => {
        return item.wid == wid
      })
      return result.length > 0
    },
    /**
 *
 */
    resizeRectHandler(code, event) {
      // 阻止事件冒泡
      event.preventDefault()


      let disX = event.clientX

      let disY = event.clientY

      let widths = []
      let heights = []
      let lefts = []
      let tops = []
      for (let index in $this.selects) {
        let _currentWidget = $this.selects[index]
        widths[index] = _currentWidget.config.width
        heights[index] = _currentWidget.config.height
        lefts[index] = _currentWidget.config.left
        tops[index] = _currentWidget.config.top
      }

      document.onmousemove = function (ev) {
        let oEvent = ev || event

        for (let index in $this.selects) {
          let _currentWidget = $this.selects[index]

          let wid = _currentWidget.wid

          let resizeWidth = widths[0]
          let resizeHeight = heights[0]
          let resizeTop = tops[0]
          let resizeLeft = lefts[0]
          let args = {
            wid: wid,
            width: resizeWidth,
            height: resizeHeight
          }
          if (code == 'br') {
            // 右下角： 鼠标当前位置 - 鼠标原本位置 + 原大小 = 拖动后的大小
            resizeWidth = oEvent.clientX - disX + widths[index]
            resizeHeight = oEvent.clientY - disY + heights[index]
            args = {
              wid: wid,
              width: resizeWidth,
              height: resizeHeight
            }
          } // end 'br'
          else if (code == 't') {
            // 中上圆角
            resizeHeight = disY - oEvent.clientY + heights[index]
            if (resizeHeight < 0) {
              return true
            }
            resizeTop = tops[index] - (disY - oEvent.clientY)
            args = {
              wid: wid,
              top: resizeTop,
              height: resizeHeight
            }
          } // end 't'
          else if (code == 'b') {
            // 中下圆角
            resizeHeight = oEvent.clientY - disY + heights[index]
            if (resizeHeight < 0) {
              return true
            }
            args = {
              wid: wid,
              height: resizeHeight
            }
          } // end 'b'
          else if (code == 'r') {
            // 中右圆角
            resizeWidth = oEvent.clientX - disX + widths[index]
            if (resizeWidth < 0) {
              return true
            }
            args = {
              wid: wid,
              width: resizeWidth
            }
          } // end 'r'
          else if (code == 'l') {
            // 中左圆角
            resizeWidth = disX - oEvent.clientX + widths[index]
            if (resizeWidth < 0) {
              return true
            }
            resizeLeft = lefts[index] - (disX - oEvent.clientX)
            args = {
              wid: wid,
              left: resizeLeft,
              width: resizeWidth
            }
          } // end 'l'
          else if (code == 'tr') {
            // 右上圆角
            resizeWidth = oEvent.clientX - disX + widths[index]
            resizeHeight = disY - oEvent.clientY + heights[index]
            resizeTop = tops[index] - (disY - oEvent.clientY)
            if (resizeHeight < 0) {
              return true
            }
            args = {
              wid: wid,
              width: resizeWidth,
              height: resizeHeight,
              top: resizeTop
            }
          } // end 'tr'
          else if (code == 'tl') {
            // 左上圆角
            resizeWidth = disX - oEvent.clientX + widths[index]
            resizeHeight = disY - oEvent.clientY + heights[index]

            if (resizeWidth >= 0) {
              resizeLeft = lefts[index] - (disX - oEvent.clientX)
            }
            if (resizeHeight >= 0) {
              resizeTop = tops[index] - (disY - oEvent.clientY)
            }
            args = {
              wid: wid,
              width: resizeWidth,
              height: resizeHeight,
              top: resizeTop,
              left: resizeLeft
            }
          } // end 'tl'
          else if (code == 'bl') {
            // 左下圆角
            resizeWidth = disX - oEvent.clientX + widths[index]
            resizeHeight = oEvent.clientY - disY + heights[index]
            resizeLeft = lefts[index] - (disX - oEvent.clientX)
            if (resizeLeft < 0) {
              return true
            }
            args = {
              wid: wid,
              width: resizeWidth,
              height: resizeHeight,
              left: resizeLeft
            }
          } // end 'bl'
          else {
            $nuxt.$emit('utils.prod', {
              error: true,
              msg: 'code 错误'
            })
          }
          args.action = 'resize'
          // 更新大小
          $nuxt.$emit('widget-update', args)
          // 更新border
          $nuxt.$emit('widget-reset-boder')
        } // end for(...)


      }

      document.onmouseup = function () {
        // 鼠标弹起时取消其他事件
        document.onmousemove = null
        document.onmouseup = null
      }
    },

    clickHandler(code) {
      utils.log('code', code)
    },
    getRefLineParams(params) {
      utils.log('params', params, Math.random())
      const {
        vLine,
        hLine
      } = params
      this.vLine = vLine
      this.hLine = hLine
    },
    // if(!!$this.cursorData){
    // //     $this.cursorData = null
    // //   }else{
    // //     $this.cursorData = 'url("/action/手.png"),default'
    // //   }

    removeEventListener() {
      $this.$design.removeEventListener('mousedown', $this.clickDrag, false)
      $this.$design.removeEventListener(
        'mousemove',
        $this.dragDesignHandler,
        false
      )
      this.cache = {
        x: 0,
        y: 0
      }
    },
    clickDrag(e) {
      e.stopPropagation()
      // 点击左键
      utils.log('点击')
      this.$design.addEventListener('mousemove', $this.dragDesignHandler, false)
    },
    /**
 * 移动画布
 * @param {*} e
 */
    dragDesignHandler(e) {
      e.stopPropagation()
      let _x = e.x,
        _y = e.y

      // 判断画布大小
      if (this.cache.x == 0 && this.cache.y == 0) {
        // 不拖动
        this.cache = {
          x: _x,
          y: _y
        }
      } else {
        // 偏移 - 向右移动为正数
        let offetx = _x - this.cache.x
        // 偏移 - 向下移动为正数
        let offety = _y - this.cache.y

        // x轴拖动 - 向右 this.transformxy.x 变大
        if (offetx > 0 && this.transformxy.x <= this.designSize.widthHalf) {
          // 向右  && 没有超过右侧
          this.transformxy.x = this.transformxy.x + offetx
        } else if (offetx < 0 && this.transformxy.x > -this.designSize.widthHalf) {
          this.transformxy.x = this.transformxy.x + offetx
        }

        // y轴拖动 - 向下 this.transformxy.y 变大
        if (offety > 0 && this.transformxy.y <= this.designSize.heightHalf) {
          this.transformxy.y = this.transformxy.y + offety
        } else if (offety < 0 && this.transformxy.y > -this.designSize.heightHalf) {
          this.transformxy.y = this.transformxy.y + offety
        }
        let args = {
          x: this.transformxy.x,
          y: this.transformxy.y
        }
        // utils.log('args',args)
        $nuxt.$emit('move-canvas', this.transformxy)
        // utils.log('left x ',this.$canvas.getBoundingClientRect().left,this.$canvas.getBoundingClientRect().x)
        // $nuxt.$emit('drag-canvas-get-coordinate', {
        //     x: this.$canvas.getBoundingClientRect().x,
        //     y: this.$canvas.getBoundingClientRect().y
        // })
        this.cache = {
          x: _x,
          y: _y
        }
      }
    },
    saveHandler() {
      utils.log('保存...')
    }
  },
  data() {
    return {
      // 
      hotBoxVisible: false,

      vLine: [],
      hLine: [],
      hoverWidget: null,
      selects: [],

      // 多选
      totalWiget: null,
      currentSelectWidget: null, // 默认选择画布
      position: null,

      cursorData: null,
      $design: null,
      $canvas: null,
      // 画布大小
      // size: {
      //     design: {
      //         width: 3000,
      //         height: 2000,
      //         // 宽的一半
      //         widthHalf: 1500,
      //         // 高的一半
      //         heightHalf: 1000,
      //     }
      // },
      transformxy: {
        x: 0,
        y: 0
      },
      // 缓存
      cache: {
        x: 0,
        y: 0
      }
    }
  }
}
